﻿@using DungeonGenerator.Java
@using PitOfDespair.Models
@using PitOfDespair.Models.Character
@model DungeonGenerator.Java.Generator
@{
    ViewBag.Title = "Index";
    var pc = Newtonsoft.Json.JsonConvert.SerializeObject(new CharacterModel());
    var npc = Newtonsoft.Json.JsonConvert.SerializeObject(new BaseCharacter());
}
@helper CheckFlair(int x, int y) {
    int cellContents = Model.GetCellContents(x, y);
    if(cellContents > 0)
    {
        <span class="flair">@cellContents</span>
    }
}
<h2>Index <span data-bind="text:currentX"></span>,<span data-bind="text:currentY"></span></h2>
@Html.ActionLink("Back to generator", MVC.Dungeon.Index())
<span data-bind="text:lastKey"></span>
<span data-bind="text:lastAction"></span>
<select data-bind="value:baseimg">
    <option value="@(Links.Content.assets.crawl_tiles_Oct_5_2010.player.@base.elf_f_png)">Elf Female</option>
    <option value="@(Links.Content.assets.crawl_tiles_Oct_5_2010.player.@base.elf_m_png)">Elf Male</option>
    
    <option value="@(Links.Content.assets.crawl_tiles_Oct_5_2010.player.@base.gnome_f_png)">Gnome Female</option>
    <option value="@(Links.Content.assets.crawl_tiles_Oct_5_2010.player.@base.gnome_m_png)">Gnome Male</option>
    
    <option value="@(Links.Content.assets.crawl_tiles_Oct_5_2010.player.@base.centaur_brown_f_png)">Centaur Female</option>
    <option value="@(Links.Content.assets.crawl_tiles_Oct_5_2010.player.@base.centaur_brown_m_png)">Centaur Female</option>

    <option value="@(Links.Content.assets.crawl_tiles_Oct_5_2010.player.@base.deep_dwarf_f_png)">Dwarf Female</option>
    <option value="@(Links.Content.assets.crawl_tiles_Oct_5_2010.player.@base.deep_dwarf_m_png)">Dwarf Male</option>
</select>
@Html.Partial(MVC.Character.Views.Details, new CharacterModel())
<img src="#" data-role="player" style="position:absolute;display:none" data-bind="visible:showPlayer,style:{top: playerTop, left: playerLeft},attr:{src:baseimg}" />
<table  id="dungeon">
    <thead>
        <tr>
            <th></th>
            @foreach (var x in Enumerable.Range(0, Model.Columns))
            {
                <th>@x</th>
            }
            <th></th>
        </tr>
    </thead>
    <tbody>
        @foreach (var y in Enumerable.Range(0, Model.Rows))
        {
            <tr><th>@y</th> @foreach (var x in Enumerable.Range(0, Model.Columns))
                            {
                                var cellType = @Model.GetCellType(x, y);
                                var cellContents = Model.GetCellContents(x, y);
                                
                                <td data-role="@cellType" style="visibility: hidden" data-x="@x" data-y="@y">@Html.Partial("Tile", cellType)@this.CheckFlair(x, y)</td>
                            }<th>@y</th></tr>
        }
    </tbody>
    <tfoot>
        <tr>
            <th></th>
            @foreach (var x in Enumerable.Range(0, Model.Columns))
            {
                <th>@x</th>
            }
            <th></th>
        </tr>
    </tfoot>
</table>
<div id="combat">
@Html.Partial(MVC.Combat.Views.Index,new CombatModel(new CharacterModel(), null,0))    
</div>

@*<canvas id="dungeon" width="600" height="600"></canvas>*@

@section scripts
{
    <script src="~/Scripts/knockout-2.1.0.js"></script>
    <script>
        ko.observable.fn.beforeAndAfterSubscribe = function(callback, target) {
            var _oldValue;
            this.subscribe(function(oldValue) {
                _oldValue = oldValue;
            }, null, 'beforeChange');
            this.subscribe(function(newValue) {
                callback.call(target, _oldValue, newValue);
            });
        };
        var DungeonModel = function(x, y, currentX, currentY) {
            var self = this;
            self.keybindings = { down: 's', up: 'w', left: 'a', right: 'd', use: 'f', take: 'g', fight: 't' };
            self.lastKey = ko.observable();
            self.lastAction = ko.observable();
            self.message = ko.observable('welcome to the pit of despair');
            self.currentX = ko.observable(+currentX);
            self.currentY = ko.observable(+currentY);
            self.showPlayer = ko.observable(true);
            self.baseimg = ko.observable();

            var walkable = function(tile) {
                return tile != '@Tile.DirtWall' && tile != '@Tile.StoneWall';
            };
            self.getTile = function(relativeX, relativeY) {
                relativeX = relativeX || 0;
                relativeY = relativeY || 0;
                var tile = $('#dungeon td[data-x=' + (+self.currentX() + +relativeX) + '][data-y=' + (+self.currentY() + +relativeY) + ']');
                return tile;
            };
            self.revealTiles = function() {


                for (var xoffset = -1; xoffset < 2; xoffset++) {
                    for (var yoffset = -1; yoffset < 2; yoffset++) {
                        var currentTile = self.getTile(xoffset, yoffset);
                        if (currentTile) {
                            $(currentTile).css('visibility', '');
                        }
                    }
                }
            };
            self.playerTop = ko.computed(function() {
                var playervis = self.showPlayer();
                var top = self.getTile().offset().top + 'px';
                console.log('getting playerTop:' + top);
                return top;
            });
            self.playerLeft = ko.computed(function() {
                var playervis = self.showPlayer();
                var left = self.getTile().offset().left + 'px';
                console.log('getting playerLeft:' + left);
                return left;
            });
            self.tryMove = function(relativeX, relativeY, desc) {
                self.lastAction(desc);
                var tile = self.getTile(relativeX, relativeY);
                if (tile.length == 0 || !walkable(tile.attr('data-role'))) {
                    self.message("can't go " + desc);
                } else {
                    self.currentX(+self.currentX() + +relativeX);
                    self.currentY(+self.currentY() + +relativeY);
                    self.revealTiles();
                }
            };


            self.revealTiles();

            $('body').on('keypress', function(e) {
                console.log('keypress');
                self.lastKey(e.which);
                switch (String.fromCharCode(e.which)) {
                case self.keybindings.left:
                    self.tryMove(-1, 0, 'west');
                    break;
                case self.keybindings.up:
                    self.tryMove(0, -1, 'north');
                    break;
                case self.keybindings.right:
                    self.tryMove(1, 0, 'east');
                    break;
                case self.keybindings.down:
                    self.tryMove(0, 1, 'south');
                    break;
                case self.keybindings.fight:
                    var targetUrl = '@Url.Action(MVC.Combat.Index())';
                    var pcParam = '@MVC.Combat.IndexParams.pc';
                    var npcParam = '@MVC.Combat.IndexParams.npc';
                    $.ajax(targetUrl+'?'+pcParam+'=@Html.Raw(pc)'+'&'+npcParam+'=@Html.Raw(npc)', {
                        success: function(data, status, jqXHR) {
                            $('#combat').html(data);
                        }
                    });
                    break;
                case self.keybindings.use:
                    //move to next level, activate switch, etc?
                    var $tile = self.getTile();
                    if ($tile && $tile.attr('data-role') === '@Tile.Downstairs') {
                        //TODO: save gear/stats
                        @{
                            var targetUrl = Url.Action(MVC.Dungeon.Details(new Random().Next(), Model.Rows, Model.Columns, Model.CurrentFeatures));
                        }
                        window.location.href = '@Html.Raw(targetUrl)';
                    }
                    break;
                default:
                    self.lastAction('unknown');
                }

                e.preventDefault();
            });

            //self.currentX(self.currentX() + 1);
            //self.currentX(self.currentX() -1);

        };

        var start = $('td[data-role=@Tile.Upstairs.ToString()]');
//find the upstairs
        var flairs = $('.flair');
        flairs.each(function(i, e) {
            var gold = $('<img src="@Links.Content.assets.crawl_tiles_Oct_5_2010.item.misc.gold_pile_png" style="position:absolute" />');
            $('#dungeon').before(gold);
            var top = $(e).parent().offset().top;
            gold.css('top', top + 'px'); //self.getTile().offset().top + 'px';
            gold.css('left', $(e).parent().offset().left + 'px');

        });
        var komodel = new DungeonModel('@Model.Columns', '@Model.Rows', $(start).attr('data-x'), $(start).attr('data-y'));

        ko.applyBindings(komodel);        
        
    </script>
    
}
